<template>
  <!-- 顶部 -->
  <div class="top">
    <div class="con">
      <div class="left">
        <!-- <span class="item">喜讯！蓝海多店铺商城上线了！</span> -->
        <!-- 消息播放 -->
        <div v-if="news.length >= 1">
          <el-carousel
            class="swiper-wrapper"
            direction="vertical"
            height="24px"
            style="overflow-y:visible; overflow-x:visible;"
          >
            <el-carousel-item
              class="swiper-slide"
              v-for="(news, index) in news"
              :key="index"
            >
              <div class="title item" @click="goNewsDet(news.id)">
                {{ news.title }}
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
        <!-- 消息播放end -->
      </div>
      <div class="right">
        <div class="item">
          <span class="text">{{language !== "en"?"欢迎来到沙鲜送":"欢迎来到沙鲜送-en"}}</span>
          <!-- <span class="text">{{language !== "en"?webConfigData.pcWelcomeCn:webConfigData.pcWelcomeEn}}</span> -->
          <span class="link" v-if="!nickName">
            <a href="javascript:void(0);" class="link-a" @click="showLoginPopup"
              >{{ $t('commonHead.login') }}</a
            >
            /
            <nuxt-link class="link-a" to="/register">{{ $t('commonHead.registration') }}</nuxt-link>
          </span>
          <span class="link" v-else>
            <a href="javascript:void(0)" class="link-name">{{ nickName }}</a>
            <span class="link-select">
              <nuxt-link to="/member-center/member-center" class="link-item"
                >{{ $t('commonHead.membershipCentre') }}</nuxt-link
              >
              <nuxt-link to="/user-center/uc-collection" class="link-item"
                >{{ $t('commonHead.myCollection') }}</nuxt-link
              >
              <nuxt-link to="/user-center/uc-coupons" class="link-item"
                >{{ $t('discountCoupon') }}</nuxt-link
              >
              <a href="javascript:void(0)" @click="loginOut" class="link-item"
                >{{ $t('commonHead.logout') }}</a
              >
            </span>
          </span>
        </div>
        <div class="item">
          <span @click="routeTo" data-route="index" class="item-a"
            >{{ $t('commonHead.mallHome') }}</span
          >
        </div>
        <div class="item">
          <span
            @click="routeTo"
            v-if="shopAuditStatus == 1"
            data-route="shopIndex"
            class="item-a"
            >{{ $t('commonHead.myShop') }}</span
          >
          <span @click="routeTo" v-else data-route="freeShop" class="item-a"
            >{{ $t('commonHead.freeShop') }}</span
          >
        </div>
        <div class="item">
          <span @click="routeTo" data-route="order" class="item-a"
            >{{ $t('commonHead.myOrder') }}</span
          >
        </div>
        <div class="item">
          <span @click="routeTo" data-route="userCenter" class="item-a"
            >{{ $t('commonHead.personalCenter') }}</span
          >
        </div>
        <div class="item mobile">
          <a href="javascript:void(0);" class="item-a">{{ $t('commonHead.mobileMall') }}</a>
          <div class="mobile-select" :style="{height:language!='zh'?'170px':'145px'}">
            <div class="code">
              <div id="qrcode"></div>
              <!-- <img src="~/assets/images/mobile-code.png" alt /> -->
            </div>
            <div class="text">{{ $t('commonHead.cellPhoneScanCodeExperience') }}</div>
          </div>
        </div>
        <!-- 顶栏购物车 -->
        <div class="item top-cart">
          <span @click="routeTo" data-route="cart" class="item-a"
            >{{ $t('commonHead.shopCart') }}({{ totalCartCount }})</span
          >
        </div>
       <!-- <div class="item">
          <span @click="switchingLanguages" class="item-a" :style="language!='zh'?'margin-right: 14px;':'margin-right: 24px;'"
            >{{ $t('commonHead.switchingLanguages') }}</span
          >
        </div> -->
        <!-- <div class="item top-cart top-cart-on" v-if="cartProdList.length">
          <span @click="routeTo" data-route="cart" class="item-a">
            购物车
            <span class="number">({{totalCartCount}})</span>
          </span>
          <div class="cart-select">
            <div class="cart-list">
              <div class="list-item" v-for="prod in cartProdList" :key="prod.prodId">
                <div class="goods-img">
                  <img :src="prod.pic" alt />
                </div>
                <div class="goods-msg">
                  <div class="name">{{prod.prodName}}</div>
                  <div class="info">
                    <span class="price">￥{{prod.price}}</span>
                    <span class="number">×{{prod.prodCount}}</span>
                  </div>
                </div>
                <div class="del" @click="delCartItem(prod.basketId)"></div>
              </div>
            </div>
            <div class="list-total">
              <div class="total-msg">
                <div class="total-number">共 {{totalCartCount}} 件商品</div>
                <div class="price">
                  ￥
                  <span class="big">{{parsePrice(totalCartAmount)[0]}}</span>
                  .{{parsePrice(totalCartAmount)[1]}}
                </div>
              </div>
              <nuxt-link to="/cart" class="total-btn">去购物车结算</nuxt-link>
            </div>
          </div>
        </div>
        <div class="item top-cart top-cart-empty" v-else>
          <span @click="routeTo" data-route="cart" class="item-a">
            购物车
            <span class="number">(0)</span>
          </span>
          <div class="no-goods">您的购物车中还没有商品，赶紧选购吧！</div>
        </div>-->
      </div>
    </div>
    <!-- 登录弹窗组件 -->
    <LoginPopup v-if="showLogin" v-on:hideLoginPop="hideLoginPop" />
    <!-- /登录弹窗组件 -->
  </div>
  <!-- /顶部 -->
</template>

<script>
import Cookie from 'js-cookie'
import LoginPopup from '~/components/login-popup'
import bus from '~/plugins/bus'
import { h5Path } from '~/plugins/config'
import { setLanguage } from '~/plugins/util.js'
import { addUrlParam } from '~/plugins/util.js'
export default {
  components: {
    LoginPopup
  },
  data () {
    return {
      showLogin: false,
      language: this.$store.state.locale,
      nickName: '',
      news: [],
      swiperOption: {
        loop: true,
        spaceBetween: 0,
        speed: 800,
        autoplay: true,
        height: 34,
        direction: 'vertical', //垂直
        autoplayDisableOnInteraction: false,
      },
      cartProdList: [], // 顶栏购物车数据
      totalCartAmount: 0,
      shopAuditStatus: null,
      shopStatus: -1,
      webConfigData: {}
    }
  },
  methods: {

    /**
     * 切换语言
     */
    switchingLanguages(){
      if( this.$store.state.locale !=='zh'){
         this.$store.commit('SET_LANGUAGE', 'zh')
         this.$i18n.locale = 'zh'
         this.language = 'zh'
      }else{
        this.$store.commit('SET_LANGUAGE', 'en')
        this.$i18n.locale = 'en'
        this.language = 'en'
      }
      // window.location.reload()
      window.location.href = addUrlParam(window.location.href, 'lang', this.language)
      // this.$router.push({path: this.$route.path, query: {...this.$route.query, lang: this.language}})
    },

    /**
     * 生成二维码
     */
    loadQRCode () {
      let qrcode = new QRCode('qrcode', {
        text: h5Path,
        width: 100,
        height: 100,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: 3
      })
    },
    /**
     * 统一跳转方法
     */
    routeTo (e) {
      let path = e.target.dataset.route
      if (path == 'index') {
        switch (path) {
          case 'index':
            this.$router.push({ path: '/' })
            break;
        }
      }
      else if (Cookie.get('token')) {
        switch (path) {
          case 'freeShop':
            this.$router.push({ path: '/user-center/uc-freeshop' })
            break;
          case 'order':
            this.$router.push({ path: '/user-center/uc-order' })
            break;
          case 'userCenter':
            this.$router.push({ path: '/user-center', query: { currentPage: '/home' } })
            break;
          case 'cart':
            this.$router.push({ path: '/cart' })
            break;
          case 'shopIndex':
            if (this.shopStatus==1) {
              this.$router.push({ path: `/shopIndex?sid=${this.shopId}` })
            } else {
              this.$message({
                type: 'warning',
                message: this.shopStatus == 0 ? this.$t('collection.storeReviewTips1') :  this.shopStatus == -1 ? this.$t('collection.storeReviewTips2') : this.$t('userCenter.theStoreOffline')
              })
            }
          default:
            break;
        }
      } else {
        this.showLogin = true
      }

    },

    /**
     * 显示登录弹窗
     */
    showLoginPopup () {
      this.showLogin = true
    },

    /**
     * 隐藏登录弹窗
     */
    hideLoginPop () {
      this.showLogin = false
      if (this.$route.path.indexOf('user-center')>-1) {
        this.$router.push({path:'/'})
      }
    },



    /**
     * 请求顶部公告
     */
    getNoticeList () {
      // 请求轮播图
      this.$axios.get('/shop/notice/topNoticeList/0').then(({ data }) => { this.news = data })
    },

    // 去公告详情
    goNewsDet (id) {
      this.$router.push({
        path: '/notice-detail',
        query: {
          id: id
        }
      })
    },

    /**
     * 退出登录
     */
    loginOut () {
      Cookie.remove('token')
      window.localStorage.clear()
      this.$route.path == '/' ? location.reload() : this.$router.push({ path: '/' })
    },

    /**
     * 获取购物车列表
     */
    getCart () {
      let shopCartParams = []
      this.$axios.post('/p/shopCart/info', shopCartParams).then(({ data }) => {
        let list = []
        data.forEach(element => {
          return element.shopCartItemDiscounts.forEach(el => {
            return list.push(...el.shopCartItems)
          })
        })
        this.cartProdList = list
      })
    },

    /**
     * 计算购物车总价
     */
    getCartAmount () {
      let basketIds = []
      this.cartProdList.forEach(el => { basketIds.push(el.basketId) })
      this.$axios.post('/p/shopCart/totalPay', basketIds).then(({ data }) => {
        this.totalCartAmount = data.finalMoney
      })
    },

    /**
     * 删除购物车商品
     */
    delCartItem (basketId) {
      let basketIds = [basketId]
      this.$axios.delete('/p/shopCart/deleteItem', { data: basketIds }).then(({ data }) => {
        this.getCart()
      })
    },
    /**
     * 价格处理
     */
    parsePrice: (value) => {
      var val = Number(value)
      if (!val) {
        val = 0;
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixed(2).split(".");
    },

    /**
     * 请求个人中心信息（店铺审核状态）
     */
    getUserCenterInfo () {
      this.$axios.get('/p/user/centerInfo', {
      }).then(({ data }) => {
        this.isSetPassword = data.isSetPassword  //是否已经设置过支付密码
        this.orderCountData = data.orderCountData  //订单状态信息
        this.shopAuditStatus = data.shopAuditStatus  //审核状态：0 未审核 1已通过 -1未通过 null 未开店
        this.shopStatus = data.shopStatus // 店铺状态(-1:未开通 0: 停业中 1:营业中 2:平台下线 3:平台下线待审核)，
        this.shopId = data.shopId  //店铺id
      })
    },
  },
  mounted () {
    // 获取网站配置信息
    this.webConfigData = JSON.parse(localStorage.getItem('webConfig') || '{}')

    // 获取个人中心信息（店铺审核状态）
    if (Cookie.get('token')) {
      this.getUserCenterInfo()
    }

    this.showLogin = Cookie.get('showLogin')
    //请求顶部公告
    this.getNoticeList()
    if (Cookie.get('token')) {
      this.nickName = localStorage.getItem('nickName')
    } else {
      this.nickName = ''
    }
    this.$nextTick(() => {
      this.loadQRCode()
    })
  },
  created () {
    bus.$on('showLogin', msg => {
      this.showLogin = msg
    })
  },
  computed: {
    totalCartCount () {
      if (!this.nickName) {
        return 0
      } else {
        return this.$store.state.cartNumber.cartNumbers;
      }
    }
  },
  watch: {
    $route (to, from) {
      //要处理的操作
      this.nickName = localStorage.getItem('nickName') ? localStorage.getItem('nickName') : ''
    }
  }
}
</script>

<style>
.left .el-carousel__indicators--vertical {
  display: none;
}
.left .swiper-slide {
  display: block !important;
  width: auto !important;
  text-align: left !important;
  font-weight: normal;
  background: inherit;
}
.swiper-slide .item {
  font-size: 12px;
}
.link-a,
.item-a {
  cursor: pointer;
}
/* 购物车数量角标 */
.total-cart-count {
  display: block;
  box-sizing: border-box;
  position: absolute;
  width: auto;
  height: auto;
  line-height: 1em;
  text-align: center;
  top: 6px;
  left: 75px;
  font-size: 12px;
  color: #fff;
  background: #e43130;
  z-index: 91;
  padding: 2px 4px;
  border-radius: 5px;
}
.total-cart-count::after {
  position: absolute;
  top: 2px;
  left: -5px;
  display: block;
  content: '';
  width: 0;
  height: 0;
  border-top: 6px solid transparent;
  border-bottom: 6px solid transparent;
  border-right: 6px solid #e43130;
}

.title {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  word-break:break-word;
  width: 187px;
}
</style>
